package com.shp.service.serviceImpl;

import com.shp.dao.GoodsDao;
import com.shp.dao.OrdersDao;
import com.shp.dao.PurseDao;
import com.shp.pojo.*;
import com.shp.service.OrdersService;
import com.shp.utils.DateUtil;
import com.shp.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZWL
 * @Version: 1.0
 * @create: 2020/2/26 15:57
 */
@Service(value = "ordersService")
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private PurseDao purseDao;

    /**
     * 立即购买
     *
     * @param request HttpServletRequest
     * @param orders  Orders
     * @param info    ResultInfo 响应前台的信息对象
     * @return ResultInfo
     */
    @Override
    public ResultInfo buyNow(HttpServletRequest request, Orders orders, ResultInfo info) {
        // 设置 订单时间
        orders.setOrder_date(DateUtil.getNowTime());
        User activeUser = (User) request.getSession().getAttribute("activeUser");
        // 设置 买家id
        orders.setUser_id(activeUser.getId());

        // 获取商品单价和数量
        Good goods = goodsDao.getGoodsById(orders.getGoods_id());
        float price = goods.getPrice();
        int number = goods.getNumber();

        // 获取订单中商品的数量
        int need_num = orders.getNeed_num();
        String order_num = UuidUtil.getUuid();

        Map<String, String> infoMap = new HashMap<>(2);
        infoMap.put("goods_num", (number - need_num) + "");
        infoMap.put("order_num", order_num);
        // 将订单编号给前台
        info.setDatas(infoMap);

        // 检验买家需求的商品数量
        if (need_num <= 0 || need_num > number) {
            info.setErrorMsg("订单错误");
            return info;
        }
        // 查询用户余额
        Purse purse = purseDao.getPurseByUserId(activeUser.getId());
        if (purse.getBalance() < (need_num * price)) {
            info.setErrorMsg("余额不足");
            return info;
        }
        info.setFlag(true);
        if (need_num == number) {
            // 设置商品状态，下架
            goodsDao.updateGoodsStatusById(0, goods.getId());
        }
        // 设置 订单价格
        orders.setOrder_price(need_num * price);

        // 设置商品的订单编号
        orders.setOrder_num(order_num);
        // 添加订单
        ordersDao.insert(orders);
        // 修改商品数量
        goodsDao.updateGoodsSizeById(goods.getId(), number - need_num);
        return info;
    }

    /**
     * 根据商品，生成订单
     *
     * @param goodsList List<Good>
     * @return List<Orders>
     */
    @Override
    public List<Orders> getOrdersByGoods(List<Good> goodsList) {

        return ordersDao.getOrdersByGoodsId(goodsList);
    }

    /**
     * 保存批量订单
     *
     * @param ordersList 订单集合
     * @return 保存成功返回true，否则返回false
     */
    @Override
    public boolean saveOrders(List<Orders> ordersList) {
        if (ordersDao.insertBatch(ordersList) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 保存批量订单，购买者钱包钱数减少，商品数量减少
     *
     * @param ordersList 批量订单集合
     * @param activeUser 购买者
     * @param orderBatch 订单的备注，交易地址，电话
     * @param info 响应对象
     * @return
     */
    @Override
    public ResultInfo saveOrdersMul(List<Orders> ordersList, User activeUser, OrderBatch orderBatch,ResultInfo info) {
        // 活跃用户id
        Integer id = activeUser.getId();
        if (orderBatch != null && ordersList != null) {
            // 将orderBatch中订单备注保存到orders中
            List<Orders> ordersList1 = orderBatch.getOrdersList();
            String address = orderBatch.getAddress();
            String phone = orderBatch.getPhone();
            String uuid = null;
            String time = DateUtil.getNowTime();
            float totalPrice = 0;
            for (Orders orders : ordersList) {
                // 生成订单编号
                uuid = UuidUtil.getUuid();
                // 获取总钱数
                totalPrice += orders.getOrder_price();
                for (Orders orders1 : ordersList1) {
                    if (orders.getGoods_id() == (int) orders1.getGoods_id()) {
                        // 设置订单属性
                        orders.setUser_id(id);
                        orders.setOrder_num(uuid);
                        orders.setOrder_note(orders1.getOrder_note());
                        orders.setAddress(address);
                        orders.setPhone(phone);
                        orders.setOrder_date(time);
                    }
                }
            }
            // 判断用户的余额是否充足
            Purse purse = purseDao.getPurseByUserId(id);
            Float balance = purse.getBalance();
            if (balance != null && balance >= totalPrice) {
                // 商品数量减少
                goodsDao.updateNumberByBatchGoodsId(ordersList);
                // 用户金额减少
                purseDao.reduceUserParseByUserId(id, totalPrice);
                // 保存订单
                this.saveOrders(ordersList);
                info.setFlag(true);
                return info;
            }else{
                info.setErrorMsg("余额不足");
                return info;
            }
        }
        info.setErrorMsg("服务器异常，请稍后重试");
        return info;
    }

    /**
     * 我买的订单
     *
     * @param userId 用户id
     * @return List<Orders>
     */
    @Override
    public List<Orders> getMyOrders(Integer userId) {
        return ordersDao.getOrdersByUserId(userId);
    }

    /**
     * 我卖的订单
     *
     * @param userId 用户id
     * @return List<Orders>
     */
    @Override
    public List<Orders> getUserOrders(Integer userId) {
        return ordersDao.getUserOrdersByUserId(userId);
    }

    /**
     * 删除订单
     * @param userId        用户id
     * @param ordersId     订单编号
     * @return true代表删除成功，false删除失败
     */
    @Override
    public boolean deleteOrdersByUserAndId(Integer userId, Integer ordersId) {
        return ordersDao.deleteByUserAndId(userId, ordersId) == 1;
    }

    /**
     * 确认收货
     *
     * @param orders 订单
     * @return true代表成功，false失败
     */
    @Override
    public boolean setOrdersStatusByUserAndId(Orders orders) {
        return ordersDao.update(orders) == 1;
    }

    /**
     * 查询所有订单，便于分页查询
     *
     * @return List<Orders>
     */
    @Override
    public List<Orders> getAll() {
        return ordersDao.getAll();
    }

    /**
     * 根据订单id，查询指定的订单
     *
     * @param id 订单id
     * @return 订单信息
     */
    @Override
    public Orders getOrders(Integer id) {
        return ordersDao.getOrdersById(id);
    }

    /**
     * 修改订单信息
     *
     * @param orders 订单信息
     * @return 修改成功返回true；否则返回false
     */
    @Override
    public boolean updateOrder(Orders orders) {
        return ordersDao.update(orders) == 1;
    }

    /**
     * 查询所有符合条件的订单
     *
     * @param orders 条件
     * @return List<Orders>
     */
    @Override
    public List<Orders> getOrdersBySelected(Orders orders) {
        return ordersDao.getOrdersBySelected(orders);
    }

    /**
     * 批量删除订单
     *
     * @param ids 订单编号
     * @return 删除成功返回true；否则返回false
     */
    @Override
    public boolean deleteOrdersBatch(Integer[] ids) {
        if(ids.length > 0){
            return ordersDao.deleteBatch(ids) > 0;
        }
        return false;
    }
}
